﻿using System;
using DMS.Dal;
using DMS.Entities;
using System.Linq;
using System.Data.Entity;
using IsolationLevel = System.Transactions.IsolationLevel;

namespace DMS.Business
{
    public class AccountService
    {
        /// <summary>
        /// tuan.tran
        /// kiem tra dang nhap
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static User ValidateLogin(string userName, string password)
        {
            using (var context = new DMSContext(IsolationLevel.ReadCommitted))
            {
               return context.Users.FirstOrDefault(x => x.UserName == userName && x.Password == password);
            }
        }

        /// <summary>
        /// tuan.tran
        /// thay doi mat khau dang nhap
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public static User ChangePassword(int userID, string oldPassword,string newPassword)
        {
            using (var context = new DMSContext(IsolationLevel.ReadCommitted))
            {
                var user= context.Users.FirstOrDefault(x => x.ID == userID && x.Password == oldPassword);

                if (user != null)
                {
                    //cap nhat mat khau moi
                    user.Password = newPassword;
                    context.SaveChanges();
                }

                return user;
            }
        }

        public static bool HasPermission(int userID, int permission)
        {
            using (var context = new DMSContext(IsolationLevel.ReadCommitted))
            {
                //var p=context.Permissions.Include(x => x.Role.Users).Select(x => new {x.RoleID, x.FID, Enumerable = x.Role.Users.Select(y=>y.ID)}).ToList();

                return context.Permissions.Include(x => x.Role.Users).Any(x => x.FID==permission && x.Role.Users.Any(y => y.ID == userID));

            }
        }
    }
}